<?php
declare (strict_types=1);

namespace app\model;

use think\model\concern\SoftDelete;

class Admin extends BaseModel
{
    use SoftDelete;

    public $errMsg = '';
    protected $insert = ['salt'];
    protected $update = ['ip'];
    protected $autoWriteTimestamp = true;
    protected $defaultSoftDelete = 0;

    public static function onBeforeWrite($model)
    {
        $id = $model->id ?? null;
        $username = $model->getData('username');
        $checkDuplication = $model->where('id', '<>', $id)->where(['username' => $username])->find();
        if ($checkDuplication) {
            $model->errMsg = lang('user.username_duplication');
            return false;
        }

        $model->last_login_ip = request()->ip();
        $model->last_login_time = time();

        return true;
    }

    public function device()
    {
        return $this->belongsToMany(Device::class, 'admin_device_relation', 'device_id', 'admin_id');
    }

    public function search(array $search)
    {
        $condition = [];
        if ($search['group_id'] ?? null) {
            $condition[] = ['group_id', '=', $search['group_id']];
        }

        return $this->where($condition);
    }

    public function setPasswordAttr($value): string
    {
        if (isset($data['salt'])) {
            $salt = $data['salt'];
        } elseif (isset($this->salt)) {
            $salt = $this->salt;
        } else {
            $salt = $this->salt = $this->setSaltAttr();
        }
        return sha1($value . $salt);
    }

    public function setSaltAttr($value = '')
    {
        return $value ?: randomStr(4);
    }

    public function checkPassword($password): bool
    {
        $password = sha1($password . $this->salt);
        return strcasecmp($password, $this->password) === 0;
    }

    public function group()
    {
        return $this->hasOne('AdminGroup', 'id', 'group_id')->bind(['group_title' => 'title']);
    }
}
